<template>
  <div class="create-plan-container">
    <el-card class="form-card">
      <div class="header-section">
        <h2>手动创建行程计划</h2>
        <el-button
            type="info"
            plain
            @click="goToHome"
            class="back-button"
            color="blue"
            background-color="blue"
        >
          返回首页
        </el-button>
      </div>
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          label-position="top"
      >
        <!-- 行程基本信息 -->
        <el-form-item label="出发地" prop="departure">
          <el-input v-model="formData.departure" placeholder="请输入出发地名称" />
        </el-form-item>

        <el-form-item label="目的地" prop="destination">
          <el-input v-model="formData.destination" placeholder="请输入目的地名称" />
        </el-form-item>

        <el-form-item label="行程天数" prop="duration_days">
          <el-input-number
              v-model="formData.duration_days"
              :min="1"
              :max="30"
              controls-position="right"
          />
        </el-form-item>

        <!-- 每日安排 -->
        <div v-for="(schedule,index) in formData.dailySchedules" :key="index">
          <el-divider>第 {{ index + 1 }} 天安排</el-divider>

          <el-form-item :label="`第 ${index + 1} 天上午活动`">
            <el-input
                v-model="schedule.morning_activity"
                type="textarea"
                :rows="2"
                placeholder="请输入上午活动安排"
            />
          </el-form-item>

          <el-form-item :label="`第 ${index + 1} 天下午活动`">
            <el-input
                v-model="schedule.afternoon_activity"
                type="textarea"
                :rows="2"
                placeholder="请输入下午活动安排"
            />
          </el-form-item>

          <el-form-item label="酒店推荐">
            <el-input
                v-model="schedule.hotel_recommendation"
                placeholder="请输入推荐酒店名称"
            />
          </el-form-item>
        </div>

        <!-- 时间范围 -->
        <el-form-item label="行程时间" prop="dateRange">
          <el-date-picker
              v-model="formData.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[
      new Date(2000, 1, 1, 9, 0, 0),
      new Date(2000, 1, 1, 18, 0, 0)
    ]"
              @change="handleDateChange"
          />
        </el-form-item>

        <!-- 预算相关 -->
        <el-form-item label="预算范围（元）">
          <el-input
              v-model="formData.budget_range"
              placeholder="例如：5000-8000"
          />
        </el-form-item>

        <el-form-item label="预算分配说明">
          <el-input
              v-model="formData.budget_allocation"
              type="textarea"
              :rows="3"
              placeholder="请输入详细的预算分配说明"
          />
        </el-form-item>

        <!-- 整体概述 -->
        <el-form-item label="行程概述">
          <el-input
              v-model="formData.overview"
              type="textarea"
              :rows="4"
              placeholder="请简要描述整体行程安排"
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="submitForm"
              :loading="isSubmitting"
          >
            提交行程计划
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive,watch } from 'vue'
import { ElMessage} from 'element-plus'
import axios from 'axios'
import index from "vuex";

import { useRouter } from 'vue-router' // Add this import

const router = useRouter() // Add this line
const formRef = ref(null)
const isSubmitting = ref(false)

// Add this function
const goToHome = () => {
  router.push('/')
}

const handleDateChange = (value) => {
  console.log('Selected Date Range:', value)
}

const formData = reactive({
  departure: '',
  destination: '',
  duration_days: 1,
  dailySchedules: Array(1).fill().map(() => ({
    morning_activity: '',
    afternoon_activity: '',
    hotel_recommendation: ''
  })),
  dateRange: [],
  budget_range: '',
  budget_allocation: '',
  overview: '',
  status: 1
})

watch(
    () => formData.duration_days,
    (newVal) => {
      const currentLength = formData.dailySchedules.length
      if (newVal > currentLength) {
        const addCount = newVal - currentLength
        for (let i = 0; i < addCount; i++) {
          formData.dailySchedules.push({
            morning_activity: '',
            afternoon_activity: '',
            hotel_recommendation: ''
          })
        }
      } else if (newVal < currentLength) {
        formData.dailySchedules.splice(newVal)
      }
    },
    { immediate: true }
)

const formRules = {
  destination: [
    { required: true, message: '目的地不能为空', trigger: 'blur' }
  ],
  duration_days: [
    { required: true, message: '请填写行程天数', trigger: 'blur' }
  ],
  dateRange: [
    {
      required: true,
      validator: (_, value, callback) => {
        if (!value || value.length !== 2) {
          callback(new Error('请选择行程日期范围'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const submitForm = async () => {
  console.log('提交数据:', JSON.stringify(formData, null, 2))
  try {
    await formRef.value.validate()

    isSubmitting.value = true
    const user = JSON.parse(localStorage.getItem('user'));
    if (!user || !user.user_id) {
      ElMessage.error('请先登录');
      return;
    }
    const user_id = user.user_id;

    const payloads = formData.dailySchedules.map((daily, index) => ({
      day_number: index + 1,
      start_time: formData.dateRange[0],
      end_time: formData.dateRange[1],
      destination: formData.destination,
      departure: formData.departure,
      duration_days: formData.duration_days,
      budget_range: formData.budget_range,
      status: 1,
      generated_by: 'manual',
      user_id: user.user_id,
      morning_activity: daily.morning_activity,
      afternoon_activity: daily.afternoon_activity,
      hotel_recommendation: daily.hotel_recommendation,
      overview: formData.overview,
      budget_allocation: formData.budget_allocation
    }))


    const { data } = await axios.post(BASE_URL+'/itinerary-details/batch-insert', payloads)

    if (data.state === 200 ) {
      ElMessage.success('行程创建成功')
      resetForm()
    } else {
      ElMessage.error(data.msg || '创建失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查表单')
  } finally {
    isSubmitting.value = false
  }
}

const resetForm = () => {
  formRef.value.resetFields()
  formData.dateRange = []
}


</script>

<style scoped>

.create-plan-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.form-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.el-divider {
  margin: 30px 0;
}

/* Add these new styles */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-button {
  margin-left: auto;
}

.create-plan-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.form-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.el-divider {
  margin: 30px 0;
}
</style>